<?php

namespace Home\Controller;

use Think\Controller;

/**
 * 公用控制器（不作权限判断）
 */
class CommunalController extends Controller
{
    public function _initialize()
    {
        if (!isset($_SESSION['userid']) || !isset($_SESSION['loginuser'])) {
            redirect(U('Login/index', '', ''));
        }
    }

    /**
     * 图片上传处理
     */
    public function uploadFace()
    {
        $obj = new \Think\Upload(); // 实例化上传类
        $obj->maxSize = C('UPLOAD_MAX_SIZE'); //图片最大上传大小
        $obj->savePath = ''; //设置文件上传（子）目录
        $obj->rootPath = C('UPLOAD_PATH') . 'face' . '/'; // 设置文件上传根目录
        $obj->saveRule = 'uniqid'; //保存文件名
        $obj->uploadReplace = true; //覆盖同名文件
        $obj->allowExts = C('UPLOAD_EXTS'); //允许上传文件的后缀名
        $obj->thumb = true; //生成缩略图
        $thumbPrefix = 'face';
        $obj->thumbPrefix = $thumbPrefix; //缩略图后缀名
        $obj->autoSub = false; //不使用子目录保存
        $obj->thumbRemoveOrigin = true; //删除原图
        $fileName = date('YmdHis', time()) . '_' . rand(100, 999);
        $obj->saveName = $fileName;
        $info = $obj->upload();
        if (!$info) {
            $this->ajaxReturn(array('status' => 0, 'msg' => $obj->getErrorMsg()), "JSON");
        } else {
            $image = new \Think\Image();
            $result['status'] = 1;
            $image->open($obj->rootPath . $info['Filedata']['savename']);
            $image->thumb(145, 165)->save($obj->rootPath . $thumbPrefix . '_' . $info['Filedata']['savename'], 'jpeg', 100, true);
            $p = $obj->rootPath . $thumbPrefix . '_' . $info['Filedata']['savename'];
            @unlink($obj->rootPath . $info['Filedata']['savename']);
            $result['path'] = $p;
            $this->ajaxReturn($result, "JSON");
        }
    }

    /**
     * 检查用户名是否重复
     */
    public function checkUser()
    {
        if (!IS_AJAX) {
            $this->error("非法请求");
        }
        $db = M('user');
        $adminUser = $db->where(array('username' => I('post.username')))->select();
        if ($adminUser) {
            $result = array("msg" => "用户名重复", "isExist" => true);
        } else {
            $result = array("msg" => "用户名可用", "isExist" => false);
        }
        $this->ajaxReturn($result, 'JSON');
    }

    /**
     * 检查角色名称是否重复
     */
    public function checkRoleName()
    {
        if (!IS_AJAX) {
            $this->error("非法请求");
        }
        $db = M('role');
        $id = I('post.id', 'intdiv');
        if ($id == -1) {
            $where = array('role_name' => I('post.rolename'));
        } else {
            $where = array('role_name' => I('post.rolename'));
            $where['id'] = array('NEQ', $id);
        }
        $role = $db->where($where)->select();
        if ($role) {
            $result = array("msg" => "角色名称重复", "isExist" => true);
        } else {
            $result = array("msg" => "角色名称可用", "isExist" => false);
        }
        $this->ajaxReturn($result, 'JSON');
    }
    /**
     * 检查菜单名称是否重复
     */
    public function checkMenuName()
    {
        if (!IS_AJAX) {
            $this->error("非法请求");
        }
        $db = M('auth');
        $id = I('post.id', 'intdiv');
        $where = array('auth_name' => I('post.menuname'));
        $where['id'] = array('NEQ', $id);
        $menu = $db->where($where)->select();
        if ($menu) {
            $result = array("msg" => "菜单名称重复", "isExist" => true);
        } else {
            $result = array("msg" => "菜单名称可用", "isExist" => false);
        }
        $this->ajaxReturn($result, 'JSON');
    }
    /**
     *获取用户菜单
     */
    public function getUserMenu()
    {
        if (!IS_AJAX) {
            $this->error("非法请求");
        }
        $where = array('user.id' => session('userid'));
        $role_auth = D('UserRoleView')->field('auth_ids,auth_desc')->where($where)->select();
        $item = [];
        $auth = '';
        $auth_ids = '';
        if ($role_auth) {
            foreach ($role_auth as $key => $value) {
                $auth_ids = $auth_ids . $value['auth_ids'] . ',';
                $auth = $auth . $value['auth_desc'] . ',';
            }
            //去除$auth中的重复值
            $auth = implode(",", array_unique(explode(',',$auth)));
        }
        session('auth', $auth);
        if ($auth_ids != '') {
            $auth_ids = substr($auth_ids, 0, strlen($auth_ids) - 1);
            //去除$auth_ids中的重复值
            $auth_ids = implode(",", array_unique(explode(',',$auth_ids)));
            $w['id'] = array('in', $auth_ids);
            $w['auth_type'] = 1;
            $menuItems = M('auth')->where($w)->select();
            /*根据easyui tree的json数据格式重新封装数据*/
            if ($menuItems) {
                foreach ($menuItems as $key => $value) {
                    $item['id'] = $value['id'];
                    $item['pid'] = $value['pid'];
                    $item['text'] = $value['auth_name'];
                    $item['state'] = $this->hasChildrens(($item['id'])) ? 'closed' : 'open';
                    $item['iconCls'] = $value['iconCls'];
                    $item['iframe'] = $value['iframe'];
                    if ($value['module'] != '' && $value['controller'] != '' && $value['method'] != '' && $value['module'] != null && $value['controller'] != null && $value['method'] != null) {
                        $item['attributes'] = array('url' => '/StudentRegistration/' . $value['module'] . '/' . $value['controller'] . '/' . $value['method']);
                    } else {
                        $item['attributes'] = array('url' => null);
                    }
                    $data[] = $item;
                }
                $this->ajaxReturn($data, 'JSON');
            } else {
                $this->ajaxReturn(array(), 'JSON');
            }
        } else {
            $this->ajaxReturn(array(), 'JSON');
        }
    }
    private function hasChildrens($id){
        $where = array('pid'=> $id,'auth_type'=>1);
        $count = M('auth')->where($where)->count();
        return $count > 0 ? true : false;
    }
    /**
     * 修改密码
     */
    public function editPwd()
    {
        $this->display();
    }

    /**
     * 修改密码操作
     */
    public function runEditPwd()
    {
        if (!IS_AJAX) {
            $this->error("非法请求");
        }
        $db = M('user');
        $old = $db->where(array('id' => session('userid')))->getField('password');
        if ($old != md5(I('post.oldpassword'))) {
            $result = array("msg" => "原始密码错误", "errorCode" => 2);
            $this->ajaxReturn($result, 'JSON');
        }
        if (I('post.repassword') != I('post.newpassword')) {
            $result = array("msg" => "两次密码不一致", "errorCode" => 3);
            $this->ajaxReturn($result, 'JSON');
        }
        $data = array(
            'id' => session('userid'),
            'password' => md5(I('post.newpassword')),
        );
        if ($db->save($data)) {
            $result = array("msg" => "操作成功", "errorCode" => 0);
        } else {
            $result = array("msg" => "操作失败", "errorCode" => 1);
        }
        $this->ajaxReturn($result, 'JSON');
    }
    public function getDepartment(){
        if (!IS_AJAX) {
            $this->error("非法请求");
        }
        $result = M('department')->select();
        $this->ajaxReturn($result, 'JSON');
    }
    public function getMajorData(){
        if (!IS_AJAX) {
            $this->error("非法请求");
        }
        $result = M('major')->where(array('deptid'=>I('post.deptId')))->select();
        $this->ajaxReturn($result, 'JSON');
    }
    public function getDormData(){
        if (!IS_AJAX) {
            $this->error("非法请求");
        }
        $deptId = I('post.deptId');
        $typeId = I('post.typeId');
        $where['id'] = array('GT',0);
        if($deptId != -1){
            $where['deptid'] = $deptId;
        }
        if($typeId != -1){
            $where['typeid'] = $typeId;
        }
        $result = M('dorm')->where($where)->select();
        $this->ajaxReturn($result, 'JSON');
    }
    public function getCurrentDormTotal(){
        if (!IS_AJAX) {
            $this->error("非法请求");
        }
        $dormId = I('post.dormId');
        $result = M('dorm')->field('spec')->where(array('id'=>$dormId))->select();
        $this->ajaxReturn($result, 'JSON');
    }
}